import axios from 'axios'
import { publicIp } from './apiIp'
import { message } from 'antd'
import '@/utils/bane'
import base64 from '../utils/base64'
import { UniteAPi } from '@/utils/Unite'
let base = new base64()

var instance = axios.create({
  //创建axios实例，在这里可以设置请求的默认配置
  timeout: 30000, // 设置超时时间10s
  baseURL: publicIp + '/api/v1/', //根据自己配置的反向代理去设置不同环境的baeUrl
  withCredentials: false, // 允许携带cookie
  retry: 2,
  retryDelay: 1000, //设置全局请求间隔
})

// 文档中的统一设置post请求头。下面会说到post请求的几种'Content-Type'
instance.defaults.headers.post['Content-Type'] = 'application/json'
instance.defaults.headers.get['Content-Type'] = 'application/json'

if (sessionStorage.getItem('loginName') != null) {
  document.cookie = 'loginName=' + sessionStorage.getItem('loginName')
}
function download(content, fileName) {
  const blob = new Blob([content]) //创建一个类文件对象：Blob对象表示一个不可变的、原始数据的类文件对象
  const url = window.URL.createObjectURL(blob) //URL.createObjectURL(object)表示生成一个File对象或Blob对象
  let dom = document.createElement('a') //设置一个隐藏的a标签，href为输出流，设置download
  dom.style.display = 'none'
  dom.href = url
  dom.setAttribute('download', fileName) //指示浏览器下载url,而不是导航到它；因此将提示用户将其保存为本地文件
  document.body.appendChild(dom)
  dom.click()
}
let arr = []
/** 添加请求拦截器 **/
instance.interceptors.request.use(
  (config) => {
    var timeNew = new Date().valueOf() //现在事件
    var timestamp = sessionStorage.getItem('timestamp') //最后获取时间
    var timeout = sessionStorage.getItem('timeout') //超时事件
    var i = 60000
    if (timeout > 900000) {
      i = 120000
    } else {
      i = 60000
    }
    // if (timeNew - timestamp > i && timeout != null) {
    //     let data = {
    //         token: sessionStorage.getItem('token'),
    //     }
    // axios
    //     .post(publicIp + '/authorize/token/update', data)
    //     .then(function (response) {
    //         var time = new Date().valueOf() // 过期时间
    //         sessionStorage.setItem('timeout', response.data.timeout * 1000) // 过期时间
    //         sessionStorage.setItem('timestamp', time) //当前登录时间
    //         sessionStorage.setItem('token', response.data.token)
    //     })
    //     .catch(function (error) {
    //         message.error('长时间未操作,请重新登录')
    //         sessionStorage.removeItem('Theuser')
    //         sessionStorage.removeItem('routeList')
    //         sessionStorage.removeItem('permissions')
    //         sessionStorage.removeItem('user')
    //         sessionStorage.removeItem('isInit')
    //         sessionStorage.removeItem('openKeys')
    //         sessionStorage.removeItem('timeout')
    //         sessionStorage.removeItem('Permission')
    //         // eslint-disable-next-line no-restricted-globals
    //         location.reload()
    //     })
    // config.url = UniteAPi(config.url)
    // config.headers['token'] = sessionStorage.getItem('token') || ''
    // config.headers['Content-Type'] = 'application/json'
    // if (sessionStorage.getItem('token')) {
    //     let arr = 'admin:' + sessionStorage.getItem('Basename')
    //     config.headers['Authorization'] =
    //         'token ' + sessionStorage.getItem('token')
    // }
    // if (config.url.includes('pur/contract/export')) {
    //     config.headers['responseType'] = 'blob'
    // }

    // if (config.url.includes('pur/contract/upload')) {
    //     config.headers['Content-Type'] = 'multipart/form-data'
    // }
    // return config
    // } else {
    config.url = UniteAPi(config.url)
    config.headers['token'] = sessionStorage.getItem('token') || ''
    config.headers['Content-Type'] = 'application/json'
    if (sessionStorage.getItem('token')) {
      let arr = 'admin:' + sessionStorage.getItem('Basename')
      config.headers['Authorization'] =
        'token ' + sessionStorage.getItem('token')
    }
    // hide = message.loading({content: 'Loading...', duration: 0});
    // 在这里：可以根据业务需求可以在发送请求之前做些什么:例如我这个是导出文件的接口，因为返回的是二进制流，所以需要设置请求响应类型为blob，就可以在此处设置。
    if (config.url.includes('pur/contract/export')) {
      config.headers['responseType'] = 'blob'
    }
    // 我这里是文件上传，发送的是二进制流，所以需要设置请求头的'Content-Type'
    if (config.url.includes('pur/contract/upload')) {
      config.headers['Content-Type'] = 'multipart/form-data'
    }
    return config
    // }
  },
  (error) => {
    // 对请求错误做些什么
    console.log(error, '错误')
    return Promise.reject(error)
  }
)

/** 添加响应拦截器  **/
instance.interceptors.response.use(
  (response) => {
    // hide()
    const res = response.data
    if (response.config.responseType === 'blob') {
      return response
    }
    if (response.status == '200') {
      // 响应结果里的statusText: ok是我与后台的约定，大家可以根据实际情况去做对应的判断
      return Promise.resolve(response.data)
    } else if (response.status == '300') {
      message.error('用户存在')
      return Promise.reject(response.data.message)
    } else if (response.status == '400') {
      message.error('响应超时')
      return Promise.reject(response.data.message)
    } else if (response.status == '201') {
      message.error(response.data.error)
      return Promise.reject(response.data.message)
    }
  },
  (error) => {
    // hide()
    if (error.response) {
      // 根据请求失败的http状态码去给用户相应的提示
      if (
        error.response.status === 402 ||
        error.response.status === 401 ||
        error.response.status === 404
      ) {
        message.error('长时间未操作,请重新登录')
        sessionStorage.removeItem('Theuser')
        sessionStorage.removeItem('timeout')
        sessionStorage.removeItem('routeList')
        sessionStorage.removeItem('permissions')
        sessionStorage.removeItem('user')
        sessionStorage.removeItem('isInit')
        sessionStorage.removeItem('openKeys')
        sessionStorage.removeItem('Permission')
        location.reload()
      }
    } else {
      return Promise.reject('请求超时, 请刷新重试')
    }
  }
)
/* 统一封装get请求 */
export const get = (url, data, config = {}) => {
  return new Promise((resolve, reject) => {
    instance({
      method: 'get',
      url: url,
      params: data,
      ...config,
    })
      .then((response) => {
        resolve(response)
      })
      .catch((error) => {
        reject(error)
      })
  })
}

/* 统一封装post请求  */
export const post = (url, data, config = {}) => {
  return new Promise((resolve, reject) => {
    instance({
      method: 'post',
      url: url,
      data,
      ...config,
    })
      .then((response) => {
        resolve(response)
        let bol = arr.every((item) => url.indexOf(item) === -1)
        if (bol) {
          // window.temp = 0
          global.constants.apply = 1
        }
      })
      .catch((error) => {
        reject(error)
      })
  })
}
/* 下载更新  */
export const downlopost = (url, fileName, data, config = {}) => {
  return new Promise((resolve, reject) => {
    instance({
      method: 'get',
      url: url,
      data,
      responseType: 'blob', //服务器返回的数据类型
    })
      .then((response) => {
        const content = response.data //返回的内容
        const fileName = response.headers.filename //文件名
        download(content, base.decode(fileName))
      })
      .catch((error) => {
        reject(error)
      })
  })
}
/* 下载更新  */
export const downloposts = (url, fileName, data, config = {}) => {
  return new Promise((resolve, reject) => {
    instance({
      method: 'post',
      url: url,
      data,
      responseType: 'blob', //服务器返回的数据类型
    })
      .then((response) => {
        const content = response.data //返回的内容
        const fileName = response.headers.filename //文件名
        download(content, base.decode(fileName))
      })
      .catch((error) => {
        reject(error)
      })
  })
}
/* 统一封装post请求  */
export const postD = (url, data, config = {}) => {
  return new Promise((resolve, reject) => {
    instance({
      method: 'post',
      url: url,
      data,
      responseType: 'blob',
      ...config,
    })
      .then((response) => {
        resolve(response)
        let bol = arr.every((item) => url.indexOf(item) === -1)
        if (bol) {
          // window.temp = 0
          global.constants.apply = 1
        }
      })
      .catch((error) => {
        reject(error)
      })
  })
}
/* 统一封装post请求  */
export const put = (url, data, config = {}) => {
  return new Promise((resolve, reject) => {
    instance({
      method: 'put',
      url: url,
      data,
      ...config,
    })
      .then((response) => {
        resolve(response)
        let bol = arr.every((item) => url.indexOf(item) === -1)
        if (bol) {
          global.constants.apply = 1
        }
      })
      .catch((error) => {
        reject(error)
      })
  })
}
/* 统一封装*/
export const Delete = (url, data, config = {}) => {
  return new Promise((resolve, reject) => {
    instance({
      method: 'Delete',
      url: url,
      data,
      ...config,
    })
      .then((response) => {
        let bol = arr.every((item) => url.indexOf(item) === -1)
        if (bol) {
          // window.temp = 0
          global.constants.apply = 1
        }
        resolve(response)
      })
      .catch((error) => {
        reject(error)
      })
  })
}
/* 统一封装post请求上传  */
export const Update = (url, data, config = {}) => {
  return new Promise((resolve, reject) => {
    instance({
      method: 'post',
      url: url,
      data,
      timeout: 10000 * 6 * 10,
      ...config,
    })
      .then((response) => {
        resolve(response)
      })
      .catch((error) => {
        reject(error)
      })
  })
}
